package epidemic

import (
	"fmt"
	"gitee.com/baal1990/epidemic/global"
	"gitee.com/baal1990/epidemic/model/common/request"
	"gitee.com/baal1990/epidemic/model/epidemic"
	epidemicReq "gitee.com/baal1990/epidemic/model/epidemic/request"
	"github.com/xuri/excelize/v2"
	"strconv"
	"strings"
	"time"
)

type EpidemicInvestigationDetailsService struct {
}

// CreateEpidemicInvestigationDetails 创建EpidemicInvestigationDetails记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationDetailsService *EpidemicInvestigationDetailsService) CreateEpidemicInvestigationDetails(epidemicInvestigationDetails epidemic.EpidemicInvestigationDetails) (err error) {
	err = global.GVA_DB.Create(&epidemicInvestigationDetails).Error
	return err
}

// DeleteEpidemicInvestigationDetails 删除EpidemicInvestigationDetails记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationDetailsService *EpidemicInvestigationDetailsService) DeleteEpidemicInvestigationDetails(epidemicInvestigationDetails epidemic.EpidemicInvestigationDetails) (err error) {
	err = global.GVA_DB.Delete(&epidemicInvestigationDetails).Error
	return err
}

// DeleteEpidemicInvestigationDetailsByIds 批量删除EpidemicInvestigationDetails记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationDetailsService *EpidemicInvestigationDetailsService) DeleteEpidemicInvestigationDetailsByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]epidemic.EpidemicInvestigationDetails{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateEpidemicInvestigationDetails 更新EpidemicInvestigationDetails记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationDetailsService *EpidemicInvestigationDetailsService) UpdateEpidemicInvestigationDetails(epidemicInvestigationDetails epidemic.EpidemicInvestigationDetails) (err error) {
	err = global.GVA_DB.Save(&epidemicInvestigationDetails).Error
	return err
}

// GetEpidemicInvestigationDetails 根据id获取EpidemicInvestigationDetails记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationDetailsService *EpidemicInvestigationDetailsService) GetEpidemicInvestigationDetails(id uint) (epidemicInvestigationDetails epidemic.EpidemicInvestigationDetails, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&epidemicInvestigationDetails).Error
	return
}

// GetEpidemicInvestigationDetailsInfoList 分页获取EpidemicInvestigationDetails记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicInvestigationDetailsService *EpidemicInvestigationDetailsService) GetEpidemicInvestigationDetailsInfoList(info epidemicReq.EpidemicInvestigationDetailsSearch) (list []epidemic.EpidemicInvestigationDetailsResult, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&epidemic.EpidemicInvestigationDetailsResult{})
	var epidemicInvestigationDetailss []epidemic.EpidemicInvestigationDetailsResult
	db = db.Table("epidemic_investigation_details A").
		Joins("join epidemic_user B on A.mobile=B.mobile").
		Joins("join epidemic_investigation_form C on A.related_form_id=C.id").
		Select("A.id,A.mobile,A.abnormal,A.related_form_id,AES_DECRYPT(FROM_BASE64(B.name), '" + global.ENCRYPTKEY_AES + "') as name," +
			"C.title,A.status,B.company,B.department,B.organization,A.remarks,A.reporte_time,A.update_time,B.location")
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.RelatedFormId != 0 {
		db = db.Where("A.related_form_id = ?", info.RelatedFormId)
	}
	if info.Name != "" {
		db = db.Where("AES_DECRYPT(FROM_BASE64(B.name), '"+global.ENCRYPTKEY_AES+"')  like ?", "%"+info.Name+"%")
	}
	if info.Status != "" && info.Status != global.DICT_INVESTIGATION_WRITE_STATUS_ALL {
		db = db.Where("A.status= ?", info.Status)
	}
	if info.Department != "" {
		if strings.Contains(info.Department, ",") {
			departments := strings.Split(info.Department, ",")
			newSls := make([]interface{}, len(departments))
			for i, v := range departments {
				newSls[i] = v
			}
			sqlStr := ""
			for range departments {
				sqlStr += "B.department= ? or "
			}
			sqlStr = strings.TrimRight(sqlStr, "or ")
			db = db.Where(sqlStr, newSls...)
		} else {
			db = db.Where("B.department= ?", info.Department)
		}
	}
	if info.Abnormal != "" {
		db = db.Where("A.abnormal= ?", info.Abnormal)
	}
	if info.Location != "" {
		db = db.Where("B.location= ?", info.Location)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Order("id desc").Find(&epidemicInvestigationDetailss).Error
	return epidemicInvestigationDetailss, total, err
}

// 导出全部
func (epidemicInvestigationDetailsService *EpidemicInvestigationDetailsService) ExportAll(relatedFormId uint) (filename string, err error) {

	var pageInfo epidemicReq.EpidemicInvestigationDetailsSearch
	pageInfo.Page = 1
	pageInfo.PageSize = 999
	pageInfo.RelatedFormId = relatedFormId
	pageInfo.Abnormal = global.DICT_INVESTIGATION_USER_STATUS_UNENABLE

	list, _, err := epidemicInvestigationDetailsService.GetEpidemicInvestigationDetailsInfoList(pageInfo)

	if err != nil {

	}
	// 获取信息
	return genExcelForExportEpidemicDetail(list)

}

// GenExcel 生成excel
func genExcelForExportEpidemicDetail(info []epidemic.EpidemicInvestigationDetailsResult) (string, error) {
	f := excelize.NewFile()
	// Create a new sheet.
	sheet := "Sheet1"
	index := f.NewSheet(sheet)
	// Set value of a cell.
	if err := genExcelTitleForEpidemicDetail(f, sheet); err != nil {
		return "", err
	}
	for i, e := range info {
		line := i + 2
		if err := genExcelLineForEpidemicDetail(e, f, sheet, line); err != nil {
			return "", err
		}
	}
	// Set active sheet of the workbook.
	f.SetActiveSheet(index)
	// Save spreadsheet by the given path.
	nowDate := time.Now().UnixNano()
	fileName := fmt.Sprintf("%s%s%d%s", global.GVA_CONFIG.System.ExportFileDir, "疫情排查异常信息", nowDate, ".xlsx")
	if err := f.SaveAs(fileName); err != nil {
		return "", err
	}
	return fileName, nil
}

// 生成标头
func genExcelTitleForEpidemicDetail(f *excelize.File, sheet string) error {
	var title = []string{
		"序号",
		"姓名",
		"手机号",
		"部门",
		"工作地",
		"标题",
		"填报状态",
		"异常状态",
		"备注",
	}
	for i := 0; i < len(title); i++ {
		axis := string(rune(65 + i))
		value := title[i]
		if err := f.SetCellValue(sheet, axis+strconv.Itoa(1), value); err != nil {
			return err
		}
	}
	return nil
}
func genExcelLineForEpidemicDetail(info epidemic.EpidemicInvestigationDetailsResult, f *excelize.File, sheet string, line int) error {
	i := 0
	if err := setCellValue(f, &i, info.ID, sheet, line); err != nil {
		return err
	}
	// 姓名
	if err := setCellValue(f, &i, info.Name, sheet, line); err != nil {
		return err
	}
	// 手机号
	if err := setCellValue(f, &i, info.Mobile, sheet, line); err != nil {
		return err
	}

	// 部门
	departmentSlice := strings.Split(info.Department, ",")
	Department := ""
	for i, e := range departmentSlice {
		tmp, _ := GetNameByKeyAndValue("department", e)
		Department += tmp
		if i+1 != len(departmentSlice) {
			Department += ","
		}
	}
	if err := setCellValue(f, &i, Department, sheet, line); err != nil {
		return err
	}

	// 常驻办公地
	Location, _ := GetNameByKeyAndValue("workcity", info.Location)
	if err := setCellValue(f, &i, Location, sheet, line); err != nil {
		return err
	}
	//标题
	if err := setCellValue(f, &i, info.Title, sheet, line); err != nil {
		return err
	}

	// 填报状态
	if err := setCellValue(f, &i, "已填", sheet, line); err != nil {
		return err
	}
	if err := setCellValue(f, &i, "异常", sheet, line); err != nil {
		return err
	}
	//备注
	if err := setCellValue(f, &i, info.Remarks, sheet, line); err != nil {
		return err
	}
	return nil
}
